<template>
<div class="wrapper" v-loading="loading">
    <!-- 浮动按钮组 -->
    <div class="bottomField">
        <el-button type="success" @click="saveEvent">保存</el-button>
        <el-button type="info">重置</el-button>
    </div>
    <div class="con">
        <!-- 表头部分 -->
        <el-divider content-position="left">
            <el-switch v-model="isPoject" active-text="项目订单" inactive-text="一般订单">
            </el-switch>
        </el-divider>
        <el-row :gutter="10">
            <el-col :span="5">
                <div class="el-input-group__prepend el-input">客户名称</div>
                <el-select v-model="customerId" filterable placeholder="选择客户" clearable @change="customerNameSelect" class="display-table-cell tableHeardInput" style="width: 100%">
                    <el-option v-for="item in customerOptions" :key="item.customer_id" :value="item.customer_id" :label="item.customer_name">
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="4">
                <el-autocomplete v-model="contactName" placeholder="输入联系人" :fetch-suggestions="contactNameSearch" value-key="contact_name" clearable @select="contactNameSelect">
                    <template slot="prepend">联系人</template>
                </el-autocomplete>
            </el-col>
            <el-col :span="4">
                <el-input v-model="telephone" placeholder="输入电话" clearable>
                    <template slot="prepend">电话</template>
                </el-input>
            </el-col>
            <el-col :span="7">
                <el-input v-model="address" placeholder="输入地址" clearable>
                    <template slot="prepend">地址</template>
                </el-input>
            </el-col>
            <el-col :span="4">
                <div class="el-input-group__prepend el-input">销售</div>
                <el-select v-model="identifierName" class="display-table-cell tableHeardInput">
                    <el-option v-for="item in identifierNameOptions" :key="item.real_name" :value="item.real_name">
                    </el-option>
                </el-select>
            </el-col>
        </el-row>
        <el-row :gutter="10" class="second" v-if="isPoject">
            <el-col :span="5">
                <div class="el-input-group__prepend el-input">项目编号</div>
                <div class="display-table-cell el-input el-input__inner prejectOrderId">{{prejectOrderId}}</div>
            </el-col>
            <el-col :span="7">
                <el-input v-model="prejectName" placeholder="输入项目名称" clearable>
                    <template slot="prepend">项目名称</template>
                </el-input>
            </el-col>
            <el-col :span="5">
                <div class="el-input-group__prepend el-input">项目负责人</div>
                <el-select v-model="projectManager" class="display-table-cell tableHeardInput">
                    <el-option v-for="item in identifierNameOptions" :key="item.real_name" :value="item.real_name">
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="7">
                <el-input v-model="projectRemark" placeholder="输入项目备注" clearable>
                    <template slot="prepend">项目备注</template>
                </el-input>
            </el-col>
        </el-row>
        <!-- 表单部分 -->
        <el-divider content-position="left">表单</el-divider>
        <vxe-table ref="xTable" :edit-config="{trigger: 'click', mode: 'cell'}" border show-overflow highlight-current-row highlight-hover-row align="center" height="450" :data="tableData" @current-change=selectRowEvent>
            <vxe-column type="seq" title="序号" width="50" fixed="left"></vxe-column>
            <vxe-column field="goodsName" title="名称" width="250" fixed="left" :edit-render="{name: '$input', props: {type: 'text',clearable: true},autoselect:'true',placeholder:'输入名称'}"></vxe-column>
            <vxe-column field="singleOrderID" title="订单编号" width="155"></vxe-column>
            <vxe-column field="category" title="类别" width="120" :edit-render="{name: '$select', options: categoryOptions,optionProps: { value: 'category_id', label: 'category_name' },placeholder:'选择类别'}"></vxe-column>
            <vxe-column field="overDate" title="交货日期" width="140" :edit-render="{name: '$input', props: {type: 'date', placeholder: '选择交货日期'}}"></vxe-column>
            <vxe-column field="material" title="材料" width="260" :edit-render="{placeholder:'选择材料'}">
                <template #edit="scope">
                    <el-select v-model="scope.row.material" size="medium" placeholder="添加材料" multiple filterable clearable>
                        <el-option v-for="item in materialOptions" :key="item.material_id" :label="item.material_name" :value="item.material_name">
                        </el-option>
                    </el-select>
                </template>
            </vxe-column>
            <vxe-column field="craft" title="工艺" width="260" :edit-render="{placeholder:'选择工艺'}">
                <template #edit="scope">
                    <el-select v-model="scope.row.craft" size="medium" placeholder="添加工艺" multiple filterable clearable>
                        <el-option v-for="item in craftOptions" :key="item.craft_id" :value="item.craft_name">
                        </el-option>
                    </el-select>
                </template>
            </vxe-column>
            <vxe-column field="specs" title="规格" width="220" :edit-render="{name: '$input', props: {type: 'text',clearable: true},autoselect:'true',placeholder:'输入规格'}"></vxe-column>
            <vxe-column field="count" title="数量" width="100" :edit-render="{name: '$input', props: {type: 'float', digits: 2,step:1},placeholder:'数量',events: {input: financeChangeEvent}}"></vxe-column>
            <vxe-column field="unit" title="单位" width="120" :edit-render="{name: '$select', options: unitOptions,optionProps: { value: 'unit_id', label: 'unit_name' },placeholder:'选择单位'}"></vxe-column>
            <vxe-column field="price" title="单价" width="100" :edit-render="{name: '$input', props: {type: 'float', digits: 2,step:1},placeholder:'单价',events: {input: financeChangeEvent}}"></vxe-column>
            <vxe-column field="amount" title="金额" width="100" :edit-render="{name: '$input', props: {type: 'float', digits: 2,step:1},placeholder:'金额',events: {input: financeChangeEvent}}"></vxe-column>
            <vxe-column field="task" title="本司任务" width="260" :edit-render="{name: '$select', options: taskOptions,optionProps: { value: 'task_id', label: 'task_name' },props: {multiple: true},placeholder:'选择本司任务'}"></vxe-column>
            <vxe-column field="outsource" title="外包" width="260" :edit-render="{name: '$select', options: taskOptions,optionProps: { value: 'task_id', label: 'task_name' },props: {multiple: true},placeholder:'选择外包'}"></vxe-column>
            <vxe-column field="remark" title="备注" width="120" :edit-render="{name: '$input', props: {type: 'text',clearable: true},autoselect:'true',placeholder:'输入备注'}"></vxe-column>
            <vxe-column title="操作" fixed="right" width="120px">
                <template slot-scope="scope">
                    <!-- <el-button type="primary" icon="el-icon-document" size="mini" @click.native.prevent="attachmentShow(scope.row)"></el-button> -->
                    <el-button type="danger" icon="el-icon-delete-solid" size="mini" @click.native.prevent="deleteTableRow(scope.$index, tableData)"></el-button>
                </template>
            </vxe-column>
        </vxe-table>
        <!-- 表单新增一行按钮 -->
        <div class="table-row-add">
            <el-button type="info" icon="el-icon-plus" @click="addTableRow">增加一行</el-button>
        </div>
        <!-- 表尾部分 -->
        <el-divider content-position="left">表尾</el-divider>
        <el-descriptions :column="6">
            <el-descriptions-item label="制单人">{{create_user_real_name}}</el-descriptions-item>
            <el-descriptions-item label="制单日期">{{create_date}}</el-descriptions-item>
            <el-descriptions-item label="最后编辑人">{{last_user_real_name}}</el-descriptions-item>
            <el-descriptions-item label="最后编辑日期">{{last_edit_date}}</el-descriptions-item>
        </el-descriptions>
    </div>
    <!-- 附件部分 -->
    <!-- <el-drawer :title="drawerTitle" :visible.sync="drawer" direction="btt" append-to-body>
        <el-carousel :interval="4000" type="card" height="200px">
            <el-carousel-item v-for="item in 6" :key="item">
                <h3 class="medium">{{ item }}</h3>
            </el-carousel-item>
        </el-carousel>
    </el-drawer> -->
</div>
</template>

<style lang="less" scoped>
.con {
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    padding: 20px;
}

.el-table {
    margin-top: 20px;
}

.table-input {
    height: 100%;

    .el-input__inner {
        border: 0px
    }
}

.second {
    margin-top: 15px;
}

.prejectOrderId {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
</style>

<script>
export default {
    data() {
        return {
            loading: true,
            isPoject: false,
            prejectOrderId: this.setprojectOrderIDMethod(),
            prejectName: '',
            projectManager: '',
            projectRemark: '',
            customerOptions: [],
            customerId: '',
            contactName: '',
            telephone: '',
            address: '',
            identifierNameOptions: '',
            identifierName: '',
            categoryOptions: [],
            craftOptions: [],
            materialOptions: [],
            unitOptions: [],
            taskOptions: [],
            tableData: [],
            create_date: new Date().toJSON().slice(0, 10),
            create_user_real_name: '伍方亮',
            last_user_real_name: '伍方亮',
            last_edit_date: new Date().toJSON().slice(0, 10),
            drawer: false,
            drawerTitle: ''
        }
    },
    methods: {
        // 客户名称选定事件
        async customerNameSelect(val) {
            if (!this.customerId) {
                this.customerId = ''
                this.contactName = ''
                this.address = ''
                this.contactName = ''
                this.telephone = ''
                return false
            }
            this.customerOptions.forEach(item => {
                if (item.customer_id === val) {
                    this.address = item.address
                }
            })
            const {
                data: contact
            } = await this.$http.post('Get_Default_Contact', {
                whereVal: this.customerId
            })
            this.contactName = contact[0].contact_name
            this.telephone = contact[0].telephone
        },
        // 联系人根据选择的客户名称远程筛选
        async contactNameSearch(queryString, cd) {
            if (!this.customerId) {
                return false
            }
            const {
                data: res
            } = await this.$http.post('Get_Some_Contacts', {
                fkval: this.customerId,
                val: queryString
            })
            cd(res)
        },
        // 联系人选定事件
        contactNameSelect(val) {
            this.telephone = val.telephone
        },
        // 销售人员名称远程查询
        async identifierNameMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Some_Identifier_Name')
            this.identifierNameOptions = res
        },
        // 系统自动设置订单编号
        setSingleOrderIDMethod(rowId) {
            var orderIDString
            var d = new Date()
            orderIDString = 'Y'
            orderIDString += String(d.getYear()).slice(1, 3)
            orderIDString += d.getMonth() + 1
            orderIDString += d.getDate()
            orderIDString += d.getHours()
            orderIDString += d.getMinutes()
            orderIDString += rowId
            return orderIDString
        },
        // 系统自动设置项目编号
        setprojectOrderIDMethod() {
            var IDString
            var d = new Date()
            IDString = 'P'
            IDString += String(d.getYear()).slice(1, 3)
            IDString += d.getMonth() + 1
            IDString += d.getDate()
            IDString += d.getHours()
            IDString += d.getMinutes()
            IDString += Math.floor(Math.random() * 9)
            IDString += Math.floor(Math.random() * 9)
            IDString += Math.floor(Math.random() * 9)
            return IDString
        },
        // 获取客户数据
        async getCustomerMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Customer')
            this.customerOptions = res
        },
        // 获取类别数据
        async getCategoryMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Category')
            this.categoryOptions = res
        },
        // 获取材料数据
        async getMaterialMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Material')
            this.materialOptions = res
        },
        // 获取工艺数据
        async getCraftMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Craft')
            this.craftOptions = res
        },
        // 获取单位数据
        async getUnitMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Unit')
            this.unitOptions = res
        },
        // 获取任务标签数据
        async getTaskMethod() {
            const {
                data: res
            } = await this.$http.post('Get_Task')
            this.taskOptions = res
        },
        async selectRowEvent({
            row
        }) {
            let str = row._XID.replace('row_', '')
            if (str.length < 3) {
                str = '0' + str
            }
            row.singleOrderID = this.setSingleOrderIDMethod(str)
        },
        financeChangeEvent({
            row,
            column
        }, {
            value
        }) {
            switch (column.property) {
                case 'count':
                    row.amount = value * Number(row.price)
                    break
                case 'price':
                    row.amount = Number(row.count) * value
                    break
                case 'amount':
                    row.price = value / Number(row.count)
                    break
            }
            // console.log(column.property)
        },
        // 本司任务与外包的唯一性选项改变
        // taskChangeEvent({
        //     row,
        //     column
        // }) {
        //     let selectCell = 'task'
        //     let checkCell = 'outsource'
        //     if (column.property === 'outsource') {
        //         selectCell = 'outsource'
        //         checkCell = 'task'
        //     }
        //     for (let index = 0; index < row[selectCell].length; index++) {
        //         row[checkCell] = row[checkCell].filter(item => {
        //             return item !== row[selectCell][index]
        //         })
        //     }
        // },
        addTableRow() {
            var list = {
                singleOrderID: '',
                goodsName: '',
                category: '',
                overDate: new Date(Date.now() + 3600 * 1000 * 24 * 7).toJSON().slice(0, 10),
                material: '',
                craft: '',
                specs: '',
                count: 0,
                unit: '',
                price: 0,
                amount: 0,
                task: [],
                outsource: [],
                remark: ''
            }
            this.tableData.push(list)
        },
        deleteTableRow(index, rows) {
            rows.splice(index, 1)
        },
        // 附件
        attachmentShow(rows) {
            this.drawer = true
            this.drawerTitle = '订单编号:' + rows.singleOrderID + '  名称:' + rows.goodsName
            // console.log(rows)
        },
        // 验证
        validate() {
            const messageStr = []
            if (!this.customerId) {
                messageStr.push('需要选择一个客户')
            }
            if (!this.contactName) {
                messageStr.push('需要填写联系人')
            }
            if (!this.address) {
                messageStr.push('需要填写地址')
            }
            // 验证表单是否存在一个有效单据
            const hasGoodsName = []
            this.tableData.forEach((item, index) => {
                item.goodsName = item.goodsName.replace(/^\s*/, '')
                if (item.goodsName) {
                    hasGoodsName.push(index)
                }
            })
            if (hasGoodsName.length === 0) {
                messageStr.push('至少需要填写一行表单信息的名称')
            }
            // 验证有效的表单类别是否为空
            let categoryCount = 0
            let taskCount = 0
            hasGoodsName.forEach(item => {
                if (!this.tableData[item].category) {
                    categoryCount += 1
                }
                if (this.tableData[item].task.length === 0 &&
                    this.tableData[item].outsource.length === 0) {
                    taskCount += 1
                }
            })
            if (categoryCount > 0) {
                messageStr.push('有' + categoryCount + '行表单信息没有选择类别')
            }
            if (taskCount > 0) {
                messageStr.push('有' + taskCount + '行表单信息至少需要一个本司任务或外包任务')
            }
            // 如果开启项目表单那么需要验证
            if (this.isPoject) {
                if (!this.prejectName) {
                    messageStr.push('需要填写项目名称')
                }
                if (!this.projectManager) {
                    messageStr.push('需要选择项目负责人')
                }
            }
            // 输出验证后的错误信息
            if (messageStr.length < 1) {
                return true
            } else {
                messageStr.forEach((str, i) => {
                    this.$message({
                        offset: 20 + (i * 40),
                        type: 'error',
                        message: str
                    })
                })
                return false
            }
        },
        // 事务方式保存订单
        async saveOrderTrans() {
            const orderVal = []
            const taskVal = []
            const outsourceVal = []
            let str = '保存'
            const projectVal = {
                project_number_id: this.prejectOrderId,
                project_manager: this.projectManager,
                project_name: this.prejectName,
                project_remark: this.projectRemark
            }
            for (let index = 0; index < this.tableData.length; index++) {
                if (!this.tableData[index].goodsName) {
                    continue
                }
                orderVal[index] = {
                    order_customer_id: this.customerId,
                    order_contact_name: this.contactName,
                    order_telephone: this.telephone,
                    order_address: this.address,
                    order_identifier_name: this.identifierName,
                    order_single_order_id: this.tableData[index].singleOrderID,
                    order_goods_name: this.tableData[index].goodsName,
                    project_id: null,
                    order_category: this.tableData[index].category,
                    order_over_date: this.tableData[index].overDate,
                    order_material: JSON.stringify(this.tableData[index].material),
                    order_craft: JSON.stringify(this.tableData[index].craft),
                    order_specs: this.tableData[index].specs,
                    order_count: this.tableData[index].count,
                    order_unit: this.tableData[index].unit,
                    order_price: this.tableData[index].price,
                    order_amount: this.tableData[index].amount,
                    order_remark: this.tableData[index].remark,
                    order_create_user_real_name: this.create_user_real_name,
                    order_create_date: this.create_date,
                    order_last_user_user_real_name: this.last_user_real_name,
                    order_last_edit_date: this.last_edit_date
                }
                taskVal[index] = []
                outsourceVal[index] = []
                for (let j = 0; j < this.tableData[index].task.length; j++) {
                    // console.log(this.tableData[index].task[j])
                    taskVal[index][j] = {
                        order_id: null,
                        task_id: this.tableData[index].task[j]
                    }
                }
                for (let j = 0; j < this.tableData[index].outsource.length; j++) {
                    outsourceVal[index][j] = {
                        order_id: null,
                        outsource_task_id: this.tableData[index].outsource[j]
                    }
                }
            }
            const {
                data: mes
            } = await this.$http.post('save_order_trans', {
                is_poject: this.isPoject,
                project_data: projectVal,
                order_data: orderVal,
                task_val: taskVal,
                outsource_val: outsourceVal
            })
            // console.log(mes)
            if (mes.query === true) {
                str = '保存'
                str += mes.queryCategory
                str += '成功！'
                str += '新增了：'
                str += mes.orderCount
                str += '条订单。'
                str += '生成了：'
                str += mes.taskCount
                str += '条工单，'
                str += mes.outsourceCount
                str += '条外包单。'
                this.$message.success(str)
            } else {
                str = '保存'
                str += mes.queryCategory
                str += '失败！'
                this.$message.error(str)
            }
        },
        // 保存按钮触发事件
        async saveEvent() {
            if (this.validate()) {
                this.saveOrderTrans()
            }
        }
    },
    async mounted() {
        await this.getCustomerMethod()
        await this.identifierNameMethod()
        await this.getCategoryMethod()
        await this.getMaterialMethod()
        await this.getCraftMethod()
        await this.getTaskMethod()
        await this.getUnitMethod()
        for (let index = 0; index < 8; index++) {
            this.addTableRow()
        }
        this.loading = false
    }
}
</script>
